package com.cskaoyan.service.wx.impl;

import com.cskaoyan.aliyun.AliyunUtils;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.cskaoyan.service.wx.WXStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author Can
 * @since 2022/06/29 15:32
 */
@Service
public class WXStorageServiceImpl implements WXStorageService {

    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Autowired
    AliyunUtils aliyunUtils;

    /**
     * wx上传图片
     * 暂且和网页端保存路径一致
     *
     * @param file
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/29 15:34
     */
    @Transactional
    @Override
    public BaseRespVo uploadImage(MultipartFile file) {

        // 先存储图片
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.indexOf("."));

        String filename = UUID.randomUUID().toString() + substring;

        // String filePath = "D:\\project2\\resource\\image";
        //
        // File destiny = new File(filePath + "\\" + filename);
        // if (!destiny.getParentFile().exists()) {
        //     destiny.getParentFile().mkdirs();
        // }
        // try {
        //     file.transferTo(destiny);
        // } catch (IOException e) {
        //     e.printStackTrace();
        //     return null;
        // }

        try {
            aliyunUtils.fileUpload(filename, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将数据保存至storage表中
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(filename);
        marketStorage.setName(originalFilename);
        marketStorage.setSize((int) file.getSize());
        marketStorage.setType(file.getContentType());
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setUrl("http://"+aliyunUtils.getOss().getBucket() + "." + aliyunUtils.getOss().getEndPoint() +"/"+ filename);

        // 设置默认值为false 表示未删除
        // LC
        marketStorage.setDeleted(false);

        int insert = marketStorageMapper.insert(marketStorage);
        BaseRespVo respVo;
        if (insert == 1) {
            respVo = BaseRespVo.ok(marketStorage);
        } else {
            respVo = BaseRespVo.invalidData("上传失败");
        }
        return respVo;
    }
}
